package org.opens.netty.chatServer.server.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.opens.netty.chatServer.message.LoginRequestMessage;
import org.opens.netty.chatServer.message.LoginResponseMessage;
import org.opens.netty.chatServer.server.service.UserServiceFactory;
import org.opens.netty.chatServer.server.session.SessionFactory;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();

        boolean loginFlag = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage loginResponseMessage = null;
        if (loginFlag) {
            loginResponseMessage = new LoginResponseMessage(true, "登录成功");
            // 将channel与username关联
            SessionFactory.getSession().bind(ctx.channel(), username);
        } else {
            loginResponseMessage = new LoginResponseMessage(false, "用户名或密码不正确");
        }
        ctx.writeAndFlush(loginResponseMessage);
    }
}
